function result=avisegment( src, bfactor, treshold, segmentsize )
% result=avisegment( src, bfactor, treshold, segmentsize ) - creates movie smaler by
% segmentsize, which contains extracted foreground with bgfactor bitmap from src with
% threshold, scaled down

result = [];
background = lumin( src(1).cdata );

% frames count, width, height
frames = size( src, 2 )

w = size( src(1).cdata, 2);
h = size( src(1).cdata, 1);

% segment sizes
sw = floor( w/segmentsize);
sh = floor( h/segmentsize);

for frame=1:(frames-1)
	% progress
	disp( sprintf('%d/%d', frame, frames-1));
	
	% get lumin
	current = lumin( src(frame).cdata );
	
	% prepare bitmap
	bitmap = abs( background - current ) > treshold;

	% update background
	background = background*(1-bfactor) + current*bfactor;
	
	% create scaled down segmented frame
	segmented = zeros( sh, sw );
	for y = 1:h
		sy = ceil( y/segmentsize );
		for x = 1:w
			sx = ceil(x/segmentsize);
			
			segmented( sy, sx )  = segmented( sy, sx ) + bitmap(y,x);
		end
	end
	
	% scale down to 0-1 range
	segmented = segmented / (segmentsize*segmentsize+1);
	
	% create resultframe
	rframe.cdata = lumi2gray( segmented );
	rframe.colormap = src(frame).colormap;

	% append to result
	result = [ result rframe];
end

	
		
	
	